<template>
  <div class="todo-app">
    <!-- 头部：标题和输入框 -->
    <TodoHeader 
      :title="appTitle" 
      @add-task="addTask" 
    />
    
    <!-- 过滤栏 -->
    <TodoFilter 
      :active-count="activeTaskCount" 
      :completed-count="completedTaskCount"
      v-model="currentFilter"
      @change-filter="setFilter"
      @clear-completed="clearCompleted"
    />
    
    <!-- 任务列表 -->
    <div v-if="filteredTasks.length === 0" class="empty-tasks">
      <template v-if="tasks.length === 0">
        暂无待办事项，请添加新任务
      </template>
      <template v-else>
        没有{{ filterLabels[currentFilter] }}的任务
      </template>
    </div>
    
    <ul v-else class="tasks-list">
      <TodoItem 
        v-for="(task, index) in filteredTasks" 
        :key="index" 
        :todo="task" 
        @toggle="toggleTask(getOriginalIndex(task))" 
        @remove="removeTask(getOriginalIndex(task))"
      />
    </ul>
    
    <!-- 底部信息 -->
    <TodoFooter 
      :app-name="appName" 
      :version="appVersion"
      @clear-all="clearAllTasks"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import TodoHeader from './TodoHeader.vue';
import TodoItem from './TodoItem.vue';
import TodoFilter from './TodoFilter.vue';
import TodoFooter from './TodoFooter.vue';

// 应用信息
const appName = 'Vue TodoList';
const appVersion = '2.0.0';
const appTitle = '我的待办事项';

// 从localStorage读取任务数据
const loadTasks = () => {
  try {
    const savedTasks = localStorage.getItem('todo-tasks');
    return savedTasks ? JSON.parse(savedTasks) : [
      { id: 1, text: '学习Vue.js', completed: false },
      { id: 2, text: '创建TodoList应用', completed: false },
      { id: 3, text: '组件化重构', completed: false }
    ];
  } catch (e) {
    console.error('读取本地存储失败', e);
    return [];
  }
};

// 任务状态
const tasks = ref(loadTasks());
const currentFilter = ref('all');

// 过滤标签
const filterLabels = {
  all: '所有',
  active: '未完成',
  completed: '已完成'
};

// 根据ID获取任务索引
const getOriginalIndex = (task) => {
  return tasks.value.findIndex(t => t.id === task.id);
};

// 生成唯一ID
const generateId = () => {
  return Date.now() + Math.floor(Math.random() * 1000);
};

// 计算属性
const activeTaskCount = computed(() => {
  return tasks.value.filter(task => !task.completed).length;
});

const completedTaskCount = computed(() => {
  return tasks.value.filter(task => task.completed).length;
});

const filteredTasks = computed(() => {
  switch (currentFilter.value) {
    case 'active':
      return tasks.value.filter(task => !task.completed);
    case 'completed':
      return tasks.value.filter(task => task.completed);
    default:
      return tasks.value;
  }
});

// 保存任务到localStorage
const saveTasks = () => {
  localStorage.setItem('todo-tasks', JSON.stringify(tasks.value));
};

// 方法
const addTask = (text) => {
  tasks.value.push({ 
    id: generateId(),
    text: text, 
    completed: false 
  });
  saveTasks();
};

const toggleTask = (index) => {
  if (index !== -1) {
    tasks.value[index].completed = !tasks.value[index].completed;
    saveTasks();
  }
};

const removeTask = (index) => {
  if (index !== -1) {
    tasks.value.splice(index, 1);
    saveTasks();
  }
};

const clearCompleted = () => {
  tasks.value = tasks.value.filter(task => !task.completed);
  saveTasks();
};

const clearAllTasks = () => {
  if (confirm('确定要清空所有任务吗？')) {
    tasks.value = [];
    saveTasks();
  }
};

const setFilter = (filter) => {
  currentFilter.value = filter;
};

// 监听任务变化自动保存（防止意外情况）
watch(tasks, saveTasks, { deep: true });

// 组件挂载
onMounted(() => {
  console.log('TodoApp组件已加载，任务数:', tasks.value.length);
});
</script>

<style scoped>
.todo-app {
  max-width: 550px;
  margin: 0 auto;
  padding: 30px;
  background-color: #f8f9fa;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.tasks-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.empty-tasks {
  text-align: center;
  padding: 30px 20px;
  color: #aaa;
  background-color: #fff;
  border-radius: 8px;
  margin: 20px 0;
  font-size: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

@media (max-width: 600px) {
  .todo-app {
    padding: 20px 15px;
    border-radius: 0;
    box-shadow: none;
  }
}
</style> 